import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import back from './back.js'
import front from './front.js'
import store from '../store/index.js'
import { Message } from 'element-ui'
Vue.use(VueRouter)
const routes = [{
    path: '/login',
    name: 'Login',
    component: Login, // 登录路由
    meta: {
      required: false
    }
  },
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/index',
    name: 'Index',
    component: () => import('../views/Index'),
    meta: {
      required: false
    },
    children: [
      ...back,
      ...front,
    ]
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home'),
    meta: {
      required: false
    },
  }
];
const router = new VueRouter({
  routes
});
router.beforeEach((to, from, next) => {
  console.log(to)
  if (to.path == '/index') { //进入主页在这里重定向
    return router.push(store.state.redirects[store.state.jobName])
      .catch(() => {});
  }
  if (Object.keys(to.meta).length) { //路由是否定义
    if (!to.meta.required) return next() // 不需要权限验证
    if (store.state.jobName && to.meta.role.includes(store.state.jobName)) { //已登录,权限符合
      store.state.isBack = to.meta.isBack //渲染对应的导航
      return next() //允许进入此页面，放行
    }
  }
  router.push(from.path).catch(() => { // 没有登录，路由没有定义,没有权限，原路径返回
    console.log('路由守卫',from.path)
    Message.error('该页面无法进入')
  })
});

export default router;

